package com.yuncheng.spcyApi.schedule;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.sys.SysConfigConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.spcyApi.service.ISpcySqsxXpjlService;
import com.yuncheng.spcyApi.service.ISysConfigService;
import com.yuncheng.spcyApi.service.IYcSysUserService;
import com.yuncheng.spcyApi.utils.SmsUtils;
import com.yuncheng.spcyApi.vo.common.ReplySmsVo;
import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.sys.SysConfigSmsVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.DateConversionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import java.util.*;

/**
 * 发送短信-定时任务
 */
@Component(value = "smsTimerTask")
public class SmsTimerTask {
    private static final Logger log = LoggerFactory.getLogger(SmsTimerTask.class);

    @Resource
    @Lazy
    private SmsUtils smsUtils;

    @Resource
    @Lazy
    private ISpcySqsxXpjlService spcySqsxXpjlService;

    @Resource
    @Lazy
    private IYcSysUserService ycSysUserService;

    @Resource
    private ISysConfigService sysConfigService;


//    private static final int timeOut = 1*60*60*1000; // 一分钟（1*60*1000）、五分钟（5*60*1000）三小时（3*60*60*1000）
//    private static final int timeOut = 1*5*60*1000; // 一分钟（1*60*1000）、五分钟（5*60*1000）三小时（3*60*60*1000）
//    private static final int timeOut = 1*60*1000; // 一分钟（1*60*1000）、五分钟（5*60*1000）三小时（3*60*60*1000）

    /**
     * 选派短信是否开启
     * @return
     */
    private SysConfigSmsVo verifySmsIsEnable(){
        SysConfigSmsVo smsVo = new SysConfigSmsVo();
        String smsFlag = Optional.ofNullable(sysConfigService.getSysConfigByCode(SysConfigConstant.FAZD_XPRY_SMS_FLAG))
                .orElseGet(()->"0");
        if (StringUtils.isBlank(smsFlag) || smsFlag.equals("0")){
            smsVo.setSendFlag(false);

            /** 默认发送短信号码 */
            String defaultPhone = Optional.ofNullable(sysConfigService.getSysConfigByCode(SysConfigConstant.MRFSHM))
                    .orElseGet(()->"18278813781");
            smsVo.setDefaultPhone(defaultPhone);
        }else {
            smsVo.setSendFlag(true);
            smsVo.setDefaultPhone("");
        }

        return smsVo;
    }

    /**
     * 定时任务-发送选派短信
     * @param xpjlId
     * @param msg
     */
    public boolean smsTimerTaskXpjlServiceNew(SpcySqsxXpjl xpjl, String xpjlId, String msg){
        try {
            if (xpjl == null){
                log.error("选派记录为空,{}",xpjlId);
                return false;
            }

            if (StringUtils.isBlank(xpjl.getFjcylxdh())){
                log.error("当前{}选派记录电话为空，{}",xpjl.getFjcyxm(),xpjlId);
                return false;
            }

            String phone = xpjl.getFjcylxdh(); // 检查员电话

            /** 是否发送短信配置 */
            SysConfigSmsVo smsVo = this.verifySmsIsEnable();
            if (!smsVo.isSendFlag()){
                phone = smsVo.getDefaultPhone();
            }

            String flag = smsUtils.sendSmsZdy(phone, msg);
            log.info("短信发送状态: {}",flag);
            if (flag.contains(BusinessConstant.SMS_FLAG)) {
                xpjl.setFsmssj(new Date());
                xpjl.setFsmszt(SpcyConstant.XPJL_SMSZT_YES);
                xpjl.setFdqrdxnr(msg);
                xpjl.setFdqrjzsj(DateUtil.offsetMinute(xpjl.getFsmssj(), 30));
                spcySqsxXpjlService.updateById(xpjl); // 更新发送时间

                ycSysUserService.updateUserGzztInZxrw(xpjl.getFuserid());

                return true;
            }

        } catch (NoSuchAlgorithmException e) {
            log.error("发送短信失败【NoSuchAlgorithmException】：{}",e.getMessage());
        } catch (IOException e) {
            log.error("发送短信失败【IOException】：{}",e.getMessage());
        } catch (InvalidKeySpecException e) {
            log.error("发送短信失败【InvalidKeySpecException】: {}",e.getMessage());
        }

        return false;
    }

    /**
     * 发生检查短信-同意选派的人员
     * */
    public Result sendSmsInJctz(String sqsxId, String xpjlId, SpcySqsxXpjl xpjl, String content){
        if (StringUtils.isBlank(sqsxId)){
            return Result.error("申请事项id不能为空");
        }

        // 选派记录
        if (xpjl == null && StringUtils.isNotBlank(xpjlId)) {
            xpjl = spcySqsxXpjlService.getById(xpjlId);
            if (xpjl == null) {
                return Result.error("选派记录不存在，请重试");
            }
        }

        // 查询电话
        String phone = ycSysUserService.findPhoneById(xpjl.getFuserid());

        boolean isSuccess = true; // 发送短信是否成功
        if (StringUtils.isBlank(phone)){
            isSuccess = false;
        }

        String flag = "0";
        try {

            /** 是否发送短信配置 */
            SysConfigSmsVo smsVo = this.verifySmsIsEnable();
            if (!smsVo.isSendFlag()){
                phone = smsVo.getDefaultPhone();
            }

            if (isSuccess) {
                flag = smsUtils.sendSmsZdy(phone, content);
            }

        } catch (NoSuchAlgorithmException e) {
            log.error("发送短信出错-【无搜索算法异常】- {}",e.getMessage());
        } catch (IOException e) {
            log.error("发送短信出错-【IOException】- {}",e.getMessage());
        } catch (InvalidKeySpecException e) {
            log.error("发送短信出错-【InvalidKeySpecException】- {}",e.getMessage());
        }

        if (!flag.contains(BusinessConstant.SMS_FLAG)) {
            isSuccess = false;
        }

        if (isSuccess){
            // 更新发送检查通知短信
            spcySqsxXpjlService.updateJctzSms(xpjl.getId(), content);

            // 发送日志
//            spcySqsxDxyxfsjlService.initDxyxFsjl(phone, jcyXm, sqsxId, content, SpcyConstant.FILE_TYPE_SMS, isSuccess);
        }

        return Result.ok("发送成功");
    }

    /**
     * 选派人员短信回复 1: 同意；2: 不同意
     * @param phone
     * @param fsmssj
     * @return
     */
    public int getXpjlSmsHfzt(String phone, Date fsmssj){
        /** 是否发送短信配置 */
        SysConfigSmsVo smsVo = this.verifySmsIsEnable();
        if (!smsVo.isSendFlag()){
            phone = smsVo.getDefaultPhone();
        }

        /** 短信回复 */
        List<ReplySmsVo> sendSmsMoInfo = smsUtils.getSendSmsMoInfo(phone, DateConversionUtils.DateToStringYYYYMMDD(fsmssj));
        if (CollectionUtil.isEmpty(sendSmsMoInfo)){
            return 0;
        }

        for (ReplySmsVo replySmsVo : sendSmsMoInfo){
            if (StringUtils.isNotBlank(replySmsVo.getContent())){
                if (replySmsVo.getContent().equals("1")){
                    return 1;
                }else if (replySmsVo.getContent().equals("2")){
                    return 2;
                }
            }
        }

        return 0;
    }
}
